package com.wxcms.ctrl;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.wxcms.domain.DepEquipments;
import com.wxcms.domain.WxProvinceDesc;
import com.wxcms.mapper.WxCpDepartDao;
import com.wxcms.mapper.WxCpUserDao;
import com.wxcms.mapper.WxProvinceDescDao;

import me.chanjar.weixin.cp.bean.WxCpDepart;
import me.chanjar.weixin.cp.bean.WxCpUser;
import net.sf.json.JSONArray;

@Controller
@RequestMapping("/admin")
public class AdminCtrl {
    Logger log=Logger.getLogger(this.getClass());
	@Autowired
	private WxCpDepartDao depdao;
	@Autowired
	private WxCpUserDao userdao;
	

	@RequestMapping(value = "/index/{province}")
	public ModelAndView index(@PathVariable String province) {

		ModelAndView modelAndView = new ModelAndView("admin/pcmain");

		return modelAndView;
	}


	@RequestMapping(value = "/edit/{province}")
	public ModelAndView edit(@PathVariable String province) {

		ModelAndView modelAndView = new ModelAndView("admin/eqedit");

		return modelAndView;
	}
	@RequestMapping(value = "/depts")
	public ModelAndView depts(HttpServletRequest request) {
		  
		Integer[] ids=(Integer[]) request.getSession().getAttribute("departids");
		 // 这是ibatis时的做法
      StringBuilder arrayString = new StringBuilder();
		 for (int j = 0, l = ids.length; j < l; j++) {
	            arrayString.append(ids[j]);
	            if (j < l - 1) {
	                arrayString.append(",");
	            }
	        }
		 log.info("\n\n\n====================="+arrayString);

		ModelAndView modelAndView = new ModelAndView("admin/depts");
		List<WxCpDepart> accounts = depdao.getDeparts(arrayString.toString(),request.getSession().getAttribute("corpid").toString());
		modelAndView.addObject("depts", accounts);
		return modelAndView;
	}
	public List<WxCpDepart> getdep(Integer id,List<WxCpDepart> Rdeps,List<WxCpDepart> deps){
       int len=deps.size();
	   if(Rdeps==null){
		 
		    Rdeps = new ArrayList<WxCpDepart>();
		    if(len>0){
		    List<WxCpDepart> Rdeps1 = new ArrayList<WxCpDepart>();
		    id=deps.get(0).getParentId();
		    for(int i = 0; i < len; i++)  {
				  WxCpDepart dep=deps.get(i);
				  log.info("=============================getdep"+dep.getName());
				if(dep.getParentId()==id){
					Rdeps1.add(dep);
					  log.info("\n=///getdep"+dep.getName()+"==="+dep.getId()); 
				}
			}
		    deps.removeAll(Rdeps1);
		    log.info("======================\n\n"+Rdeps1.size()+"===="+Rdeps.size());
		    Rdeps.addAll(Rdeps1);
		    int len1=Rdeps1.size();
			    for(int i = 0; i < len1; i++)  {
			    	WxCpDepart dep=Rdeps1.get(i);
			        getdep(dep.getId(),Rdeps,deps);
			    }
		    }
		 
		    
		}else{
			List<WxCpDepart> Rdeps1 = new ArrayList<WxCpDepart>();
		   for(int i = 0; i < len; i++)  {
	
			   WxCpDepart dep=deps.get(i);
				 log.info("=============================getdep12222222"+dep.getName()+"=="+dep.getParentId()+"=="+id);
	//		for(WxCpDepart dep:deps){
			
				if(dep.getParentId()==id){
					Rdeps1.add(dep);
				 
					//getdep(dep.getId(),Rdeps,deps);
				}
			}
		   deps.removeAll(Rdeps1);
		   log.info("======================\n\n"+Rdeps1.size()+"===="+Rdeps.size());
		   Rdeps.addAll(Rdeps1);
		   int len1=Rdeps1.size();
		    for(int i = 0; i < len1; i++)  {
		    	WxCpDepart dep=Rdeps1.get(i);
		        getdep(dep.getId(),Rdeps,deps);
		    }
		    
		   
		   
		   log.info("======================\n\n"+len+"===="+Rdeps.size());
		}
		return Rdeps;
	
	}

	@RequestMapping(value = "/depts_json")
	public @ResponseBody JSONArray depts_json(HttpServletRequest request) {
		  
		Integer[] ids=(Integer[]) request.getSession().getAttribute("departids");
		 // 这是ibatis时的做法
        StringBuilder arrayString = new StringBuilder();
		 for (int j = 0, l = ids.length; j < l; j++) {
	            arrayString.append(ids[j]);
	            if (j < l - 1) {
	                arrayString.append(",");
	            }
	        }
 
        JSONArray json=new JSONArray();
		List<WxCpDepart> accounts = depdao.getDeparts(arrayString.toString(),request.getSession().getAttribute("corpid").toString());
		//accounts=getdep(1,null,accounts);
		json=JSONArray.fromObject(accounts);

		 return json;
	}
	@RequestMapping(value = "/members/{depid}")
	public ModelAndView members(@PathVariable String depid) {
		ModelAndView modelAndView = new ModelAndView("admin/members");
		List<WxCpUser> accounts = userdao.getUsers(depid);
		modelAndView.addObject("menbers", accounts);

		return modelAndView;
	}
	@RequestMapping(value = "/dmembers")
	public ModelAndView dmembers(HttpServletRequest request,@RequestBody List<String> list) {
		ModelAndView modelAndView = new ModelAndView("admin/members");
		
		List<WxCpUser> accounts = userdao.getdUsers(list,request.getSession().getAttribute("corpid").toString());
		
		modelAndView.addObject("menbers", accounts);

		return modelAndView;
	}
	/**
	 * 保存设备扩展信息 配置 ，返回 执行完成  
	 * 统一接口返回
	 * 
	 * */
 	@RequestMapping(value = "/updateDetail")
 
	public @ResponseBody JSONObject updateDetail(@RequestBody List<DepEquipments> list) {
//		ModelAndView modelAndView = new ModelAndView("common/handleResult");
	    JSONObject jsobj= new JSONObject();
	
		try {
			depdao.updateDetail(list);
		    jsobj.put("success", true);
		} catch (Exception e) {
			// TODO: handle exception
		    jsobj.put("success", false);
		}
	   
 		return  jsobj;
		 

//		return modelAndView;
	}
	

	//@RequestMapping(value = "/eqpdetail/{id}",produces="text/HTML")
	public ModelAndView equipments(HttpServletRequest request,@PathVariable String id) {

		ModelAndView modelAndView = new ModelAndView("admin/eqpfull");
		//20160720 -------------
	    //获取当前用户的职位信息
	     Object position= request.getSession().getAttribute("position"); 
	     // 判断是否管理组职位
	     String depids="";
	    if((position!=null)&&(position.toString().contains("admin"))){
	    
	    } else{
	    	 Integer[] deps=	(Integer[]) request.getSession(false).getAttribute("depids");
			  depids=StringUtils.join(deps,",");
	    }
	    

	    
		List<DepEquipments> equipments = depdao.getEqpDetail(id, depids);
		modelAndView.addObject("equipments", equipments);

		return modelAndView;
	}
	@RequestMapping(value = "/eqpddetail_json" )
	public @ResponseBody JSONArray equipment_json(HttpServletRequest request,@RequestParam(value = "depids", required = false, defaultValue = "") String depids) {
		JSONArray json=new JSONArray();;
 
	    Object position= request.getSession().getAttribute("position"); 
 
		List<DepEquipments> equipments = depdao.getdEqpDetail( depids,request.getSession().getAttribute("corpid").toString());
	 
		json=JSONArray.fromObject(equipments);

		 return json;
	}

	@RequestMapping(value = "/eqpddetail",produces="text/HTML")
	public ModelAndView dequipments(HttpServletRequest request,@RequestParam(value = "depids", required = false, defaultValue = "") String depids) {

		ModelAndView modelAndView = new ModelAndView("admin/eqpfull");
		//20160720 -------------
	    //获取当前用户的职位信息
	     Object position= request.getSession().getAttribute("position"); 
	     // 判断是否管理组职位
//	     String depids="";
//	   
//	    	 Integer[] deps=	(Integer[]) request.getSession(false).getAttribute("depids");
//			  depids=StringUtils.join(deps,",");
	    
  
		List<DepEquipments> equipments = depdao.getdEqpDetail( depids,request.getSession().getAttribute("corpid").toString());
		modelAndView.addObject("equipments", equipments);

		return modelAndView;
	}
	
	@RequestMapping(value = "/addequipment")
	public ModelAndView addequipment(HttpServletRequest request,@RequestParam(value = "depid", required = false, defaultValue = "1") String depid,
			@RequestParam(value = "eqpids", required = false, defaultValue = "") String eqpids) {

		if (!eqpids.isEmpty()) {

			String[] ids = eqpids.split(",");
			if (ids.length > 0) {

				depdao.deletebydepid(depid,request.getSession().getAttribute("corpid").toString());

				List<DepEquipments> deps = new ArrayList<DepEquipments>();

				for (int i = 0; i < ids.length; ++i) {

					DepEquipments dep = new DepEquipments();
					dep.setDepid(depid.trim());
					dep.setPuid(ids[i].trim());

					deps.add(dep);
				}

				depdao.addEquipments(deps,request.getSession().getAttribute("corpid").toString());
			}
		}

		ModelAndView modelAndView = new ModelAndView("equip/equipments");
		
	    
		List<DepEquipments> equips = depdao.getEquipments(depid,request.getSession().getAttribute("corpid").toString());
		modelAndView.addObject("equipments", equips);

		return modelAndView;
	}

}
